<template>
  <div class="bigbox">
    <!-- 页面搜索栏盒子 -->
    <div class="topbox" :style="{height:isheight+'px'}">
      <el-form :model="form" label-position="left" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="建筑群">
              <!-- <el-select size="small" v-model="form.buildingId" @change="changeqiye">
                <el-option v-for="(item,index) in qiyelist" :key="index" :label="item.name" :value="item.id" class="option"></el-option>
              </el-select> -->
              <FilterSelect2
                    v-model="form.buildingId"
                    :optionlist="qiyelist"
                    @updateModelValue="changeqiye"
                    :valuekey="{ name: 'name', value: 'id' }"
                  ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="用能类型">
              <el-select size="small" v-model="form.energyType" style="width: 100%;">
                <el-option v-for="(item,index) in yomgnenglist" :key="index" :label="item.text" :value="item.value" class="option"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="分摊方式" >
              <el-select size="small" v-model="form.type" style="width: 100%;">
                <el-option v-for="(item,index) in fentanlist" :key="index" :label="item.text" :value="item.value" class="option"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="公共表计">
              <!-- <el-select size="small" v-model="form.meterId">
                <el-option v-for="(item,index) in meterlist" :key="index" :label="item.meterName" :value="item.meterId" class="option"></el-option>
              </el-select> -->
              <FilterSelect2
                    v-model="form.meterId"
                    :optionlist="meterlist"
                    :valuekey="{ name: 'meterName', value: 'meterId' }"
                  ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="4" v-show="isshowdate">
            <el-form-item label="月份">
              <el-date-picker
                style="width: 100%;"
                size="small"
                value-format="yyyy-MM"
                v-model="form.month"
                type="month"
                placeholder="选择月">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="isshowdate?24:4" style="text-align: right;">
                <el-button @click="chongzhi" size="small" >重 置</el-button>
                <el-button @click="getdatalist()" type="primary" size="small" >查 询</el-button>
                <el-button type="text" v-if="isshowdate"  @click="zedie" >收起 <i class="el-icon-arrow-up"></i> </el-button>
                <el-button type="text"  v-else  @click="zedie" >展开 <i class="el-icon-arrow-down"></i> </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="bodybox" :style="{height:isshowdate?'calc(100% - 150px)':'calc(100% - 90px)'}">
      <div class="title">
        <div>分摊记录</div>
        <div><TopTile  @command="command" @daochu="daochu" @shuaxin="shuaxin"></TopTile></div>
      </div>
      <div class="tablebox">
      <template>
          <el-table
          :header-cell-style="{'text-align':'center',background:'#f5f5f5'}"
          v-loading="loading"
          border
          height="calc(100% - 1px)"
          :data="tableData" 
          @expand-change="expandChange"
          :size="issize"
            style="width: 100%">
            <template slot="empty">
              <el-empty description="暂无数据"></el-empty>
            </template>
            <el-table-column type="expand">
              <template slot-scope="props">
                <div style="padding: 10px 10px 10px 30px;background-color: #f2f8ff;">
                  <el-table
                   border
                  :header-cell-style="{'text-align':'center',background:'#f5f5f5'}"
                  :data="props.row.apportionMeterChildrenList"
                  style="width: 100%">
                  <el-table-column
                    prop="meterName"
                    label="分摊表计">
                  </el-table-column>
                  <el-table-column
                    prop="customerName"
                    label="用户名称">
                  </el-table-column>
                  <el-table-column
                    prop="roomName"
                    label="房间名称">
                  </el-table-column>
                  <el-table-column
                    prop="ratio"
                    label="分摊比例(%)">
                  </el-table-column>
                  <el-table-column
                    prop="consumption"
                    label="分摊用量(kWh/吨)">
                  </el-table-column>
                  <el-table-column
                    prop="fee"
                    label="分摊费用(元)">
                   </el-table-column>
                   <el-table-column
                    prop="recordTime"
                    align="center"
                    label="分摊日期">
                   </el-table-column>
                   <el-table-column
                    align="center"
                    prop="status"
                    label="分摊状态">
                   </el-table-column>
                  </el-table>
                 <!-- <div class="jisuanzong">
                  <div class="left">合计</div>
                  <div class="right">
                    <div class="text">100</div>
                    <div class="text">68</div>
                    <div class="text">88.4</div>
                  </div>
                 </div> -->
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="建筑群名称"
              width="200"
              prop="buildingName">
            </el-table-column>
            <el-table-column
              label="表计名称"
              prop="meterName">
            </el-table-column>
            <el-table-column
              label="月份"
              align="center"
              prop="statisticsMonth">
            </el-table-column>
            <el-table-column
              label="分摊方式"
              prop="typeName">
            </el-table-column>
            <el-table-column
              label="分摊模型"
              prop="modelName">
            </el-table-column>
            <el-table-column
              label="分摊日期"
              align="center"
              prop="dayOfMonth">
            </el-table-column>
            <el-table-column
              label="开始时间"
              align="center"
              prop="startTime">
            </el-table-column>
            <el-table-column
              label="结束时间"
              align="center"
              prop="endTime">
            </el-table-column>
            <el-table-column
              label="总用电量(kWh/吨)"
              prop="totalConsumption"
              width="150"
              align="right">
            </el-table-column>
            <el-table-column
              label="总费用(元)"
              align="right"
              prop="totalFee">
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="200">
              <template #default="{row}">
                <span>
                  <el-button @click="areyousure(row)" v-show="row.confirmStatus=='未确认'" size="small" 
                  style="margin-right: 5px;" :type="!row.isshow?'warning':'primary'">确 认</el-button>
                  <template >
                    <el-popconfirm
                      @confirm="chongsuan(row)"
                      title="确定将此条数据重算吗？"
                    >
                      <el-button v-show="row.confirmStatus=='未确认'" slot="reference" size="small" type="primary">重 算</el-button>
                    </el-popconfirm>
                    </template>
                  <!-- <el-button v-show="row.confirmStatus=='未确认'" type="primary" size="small" @click="chongsuan(row)">重 算</el-button> -->
                  <el-button v-show="row.confirmStatus=='已确认'" size="small" type="info" plain disabled>已确认</el-button>
                </span>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
      <!-- 底部分页 -->
      <div class="fenye">
          <el-pagination
                background
                layout="prev, pager, next"
                :current-page.sync="pageobj.pageNo"
                :page-size="20"
                @current-change="getdatalist"
                :total="+totalCount">
          </el-pagination>
        </div>
    </div>
  </div>
</template>

<script>
import {exportexcel} from '@/utils/excel'
import TopTile from '@/components/TopTitle/index.vue'
import TableColumn from '@/components/Table/index.vue'
import { getzidianxialaapi } from '@/api/guidelines'
import {gettablelistapi} from '@/api/prwpaid/file-management/meter'
import { getloginlistapi } from '@/api/prwpaid/file-management/Architectural-complex'
import {getsharerecordapi,getcordxiangqingapi,postsureapi,postchongsuanapi} from '@/api/prwpaid/shares/share-record'
export default {
  name: 'CallPoliceIndex',
  components: {
    TopTile,
    TableColumn
  },
  data() {
    return {
      loading:false,
      totalCount:'',
      issize: 'medium',
      form: {buildingId:'',energyType:'',type:'',meterId:'',month:''},
      qiyelist: [],
      yomgnenglist: [],
      fentanlist: [],
      meterlist:[],
      tableData:[],
      pageobj: {
        pageNo: 1,
        pageSize:20
      },
      isshowdate: false,
      isheight: 80,
    };
  },

  async mounted() {

  // 获取分摊类型
  const fentan = await getzidianxialaapi({ dictType: 'MBM_APPORTIONMENT_TYPE' })
  this.fentanlist = fentan.data.list
  // 获取用能类型
  const yonghu = await getzidianxialaapi({ dictType: 'MBM_ENERGY_TYPE' })
    this.yomgnenglist = yonghu.data.list
    // 获取建筑群
    const res = await getloginlistapi()
    this.qiyelist = res.data.list
    const localbuildingId = localStorage.getItem('buildingId')
    const isBuildIdInArray = this.qiyelist.some(item => item.id == localbuildingId);
    if(isBuildIdInArray){
      this.form.buildingId = localbuildingId ? localbuildingId : ''
    }else{
      this.form.buildingId = ''
    }

    // 获取表计
    const meter = await gettablelistapi({ buildingId:this.form.buildingId,roomId:'',name:'',gatewayName:'',status:'', pageNo:0, pageSize: 500 })
    this.meterlist=meter.data.list
    this.getdatalist()
  },

  methods: {
    // 企业下拉
    async changeqiye(val) {
          // 获取表计
    const meter = await gettablelistapi({ buildingId:val,roomId:'',name:'',gatewayName:'',status:'', pageNo:0, pageSize: 500 })
    this.meterlist=meter.data.list
      localStorage.setItem('buildingId', val)
    },
    async chongsuan(row) {
      await postchongsuanapi(row.mainRecordId).then(res => {
        this.$message({
          type: res.code == '200' ? 'success' : 'warning',
          message: res.code == 200 ? '重算成功':res.message
        })
      })
    },
    // 确认
    async areyousure(row) {
      if(!row.isshow) return this.$message.warning('此数据需于次月一号后方可操作')
      this.$confirm('是否确认?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await postsureapi({ mainRecordId: row.mainRecordId }).then(res => {
        this.$message({
          type: res.code == '200' ? 'success' : 'warning',
          message: res.code == 200 ? '操作成功':res.message
        })
      })
      this.getdatalist()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消确认'
          })
        })
    },
    // 表格点击事件
    async expandChange(row) {
      let { data: { list } } = await getcordxiangqingapi({ mainRecordId: row.mainRecordId })
      this.tableData.forEach(ele => {
        if (ele.mainRecordId == row.mainRecordId) {
          ele.apportionMeterChildrenList=list
        }
      })
    },
    // 获取表格数据
    async getdatalist() {
      this.loading=true
      const { data: { list, totalCount } } = await getsharerecordapi({
        pageNo: this.pageobj.pageNo - 1,...this.form,
        pageSize: this.pageobj.pageSize,
      })
      const currentDate = new Date();
      list.forEach(ele => {
        ele['apportionMeterChildrenList'] = []
        const [year, month] = ele.statisticsMonth.split('-').map(Number);
        let nextMonthYear = year;
        let nextMonth = month + 1;
        if (nextMonth === 13) {
            nextMonth = 1;
            nextMonthYear++;
        }
        const nextMonthFirstDay = new Date(nextMonthYear, nextMonth - 1, 1);
        ele['isshow'] = currentDate >= nextMonthFirstDay;
      })
      console.log(list);
      this.tableData = list
      this.totalCount = totalCount
      this.loading=false
    },
    // 导出
    daochu() {
      exportexcel('mbm-microservice-biz/mbm/apportionment/record/exportExcel', {...this.form},'分摊记录')
    },
    // 刷新
    shuaxin() {
      this.getdatalist()
      this.$message.success('列表刷新成功')
    },
    // 调节表格密度
    command(val) {
        if (val === '默认') {
          this.issize = 'medium'
        } else if (val === '中等') {
          this.issize = 'small'
        } else {
          this.issize = 'mini'
        }
    },
    // 重置
    chongzhi() {
      localStorage.removeItem('buildingId');
      this.form = { buildingId: '', energyType: '', type: '', meterId: '', month: '' }
      this.getdatalist()
    },
        // 折叠导航栏
    zedie () {
      this.isshowdate = !this.isshowdate
      if (this.isshowdate) {
        this.isheight = 140
      } else {
        this.isheight = 80
      }
    },
  },
};
</script>

<style scoped>
/* *{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
} */
.option{
  padding-left: 10px;
}
.bigbox{
  padding: 10px;
  height: 100%;
  .topbox{
    height: 80px;
    padding:20px;
    background-color: #fff;
    margin-bottom: 10px;
  }
  .bodybox{
    background-color: #fff;
    padding: 20px;
    .title{
      display:flex;
      justify-content:space-between;
    }
    .tablebox{
      margin-top: 10px;
      height: 88%;
      .button{
      width: 60px;
      height: 30px;
      margin-left: 10px;
      border: 1px solid #ccc;
      border-radius: 3px;
    }
   .jisuanzong{
    display: flex;
    height: 40px;
      line-height: 40px;
    .left{
      width: 50%;
      text-align: center;
      background-color: #f1f1f1;
    }
    .right{
      width: 50%;
      display: flex;
      background-color: #fff;
      .text{
        width: 33.3%;
        text-align: center;
      }
    }
   }
    }
    .fenye{
      text-align: right;
      margin-top: 10px;
    }
  }
}
::v-deep .el-table__expand-icon{
 -webkit-transform: rotate(0deg);
 transform: rotate(0deg);
}
 /*2.展开按钮未点击的样式是加号带边框*/
 ::v-deep .el-table__expand-icon .el-icon-arrow-right:before{
   content: "\e6d9";
   border: 1px solid #ccc;
   padding: 1px;
 }
  /*2.按钮已点击展开之后的样式是减号带边框*/
  ::v-deep .el-table__expand-icon--expanded .el-icon-arrow-right:before{
  content: "\e6d8";
}
::v-deep .el-table__expand-icon--expanded:hover {
  color: #409eff;
}
::v-deep .el-icon-arrow-right:hover {
  color: #409eff;
}
</style>